<?php

function reequipment_userapi_getcompanyid($args)
{	
	extract($args);
	// Do the company id from the session if it is there.
	$company_id = xarSessionGetVar('company_id');
	// If it is not there, look for it in the url
	if (empty($company_id)){
    	$company_id = $company_id_from_url;
    }
  	// return var_export($company_id);
    // Check to make sure this uid is allowed for this company
    $uid = xarSessionGetVar('uid');
    if (!empty($company_id)){
    	if (!xarModAPIFunc('reequipment', 'user', 'checkuserincompany', array('user_id' => $uid, 'company_id' => $company_id))) return; 
    	// If it makes it past this, set the company id in the session.
    	xarSessionSetVar('company_id', $company_id);
    	// xarSessionSetVar('company_name', $company_name);
    } else {
    	// How many companies is the user assigned to?
   		$count = xarModAPIFunc('reequipment', 'user', 'countcompaniesforuser', array('user_id' => $uid));
   		// If they are assigned to more than one, then allow them to change companies
   		if ($count > 1) {
   			xarSessionSetVar('change_companies_allowed', true);
   			// company_id is not set at this point, so redirect to the url to set the company
   			// In the change companies function, we have to clear the session var first thing.
   			xarResponseRedirect(xarModURL('reequipment', 'user', 'change_company'));
   		} else {
   			// We just need to get the company id for this user and set it in the session
   			$company = xarModAPIFunc('reequipment', 'user', 'getrel', array('user_id' => $uid));
   			foreach ($company as $var){
			// make sure it is an integer.
				$company_id = intval($var['company_id']);
			}
			// Now it's in the session at least until the next check.
			xarSessionSetVar('company_id', $company_id);
		}
	}
    return true;
}
?>